
/* -----------------
* brief 
* 1. this is code gen by tools
*/

package service

import (
	"fmt"
	mchcorev2 "github.com/chanxuehong/wechat/mch/core"
	"github.com/chanxuehong/wechat/mchv3/marketing/busifavor"
	"saas_sys_base/common"
	. "saas_sys_base/modules/coupon/models"

)

type CouponApiService struct {
	// add your model here
	mchCouponService MchCouponService
	wxCouponService WxCouponService
}

func (t *CouponApiService) CreateCouponByWho(who *common.Who, couponPara *busifavor.MchCoupon, CouponMode common.COUPON_MODE) (*MchCoupon, *busifavor.CreateBusiFavorStockResp, error) {
	var err error
	var resp *busifavor.CreateBusiFavorStockResp
	if (CouponMode & common.COUPON_MODE_WX) != 0 { //如果是兼容微信模式
		resp, err = t.wxCouponService.CreateCouponByWho(who, couponPara)
	}

	if err != nil {
		return nil, nil, err
	}

	couponDb, err :=t.mchCouponService.CreateCouponByWho(who, couponPara, resp, CouponMode)
	if err != nil {
		return nil, nil, err
	}

	return couponDb, resp, nil
}

func (t *CouponApiService) GetCouponSign(who *common.Who, StockID string, OutRequestNo string) (*MchCoupon, string, *mchcorev2.SendCouponParams, error) {
	couponDb := t.mchCouponService.GetMchCouponByStockId(StockID)
	if couponDb == nil {
		return nil, "", nil, fmt.Errorf("not found stockId<%s>", StockID)
	}

	if (couponDb.CouponMode & common.COUPON_MODE_WX) == 0 { //如果是兼容微信模式
		return nil, "", nil, fmt.Errorf("GetCouponSign fail: coupon mode must be wx, couponId<%d>", couponDb)
	}

	sendCouponParams := []mchcorev2.SendCouponParams{{StockId: couponDb.StockId, OutRequestNo: OutRequestNo}}
	sign, err  := t.wxCouponService.GetCouponSign(who, sendCouponParams, couponDb.BelongMerchant)
	if err != nil {
		return nil, "", nil, err
	}
	return couponDb, sign, &sendCouponParams[0], nil
}

func (t *CouponApiService) GetCouponCallback(who *common.Who) (*busifavor.GetCallbackResp, error) {
	return t.wxCouponService.GetCouponCallback(who)
}